package com.glsc.ngateway.platform.service.it;

import cn.hutool.core.util.StrUtil;
import com.glsc.ngateway.common.api.platform.dto.user.PlatformUserDto;
import com.glsc.ngateway.common.base.domain.mysql.gateway.platform.it.ItCloudDevice;
import com.glsc.ngateway.common.base.domain.mysql.gateway.platform.it.ItCloudList;
import com.glsc.ngateway.common.base.domain.mysql.gateway.platform.User;
import com.glsc.ngateway.common.api.platform.dto.it.CloudManageExport;
import com.glsc.ngateway.common.base.domain.mysql.gateway.platform.it.ItServerDevice;
import com.glsc.ngateway.common.base.domainmapper.CloudRowMapper;
import com.glsc.ngateway.common.base.repo.mysql.gateway.platform.it.ItCloudDeviceRepo;
import com.glsc.ngateway.common.base.repo.mysql.gateway.platform.it.ItCloudListRepo;
import com.glsc.ngateway.platform.service.MailService;
import com.glsc.ngateway.platform.service.UserService;
import com.glsc.ngateway.platform.service.costallocation.BusiSystemInfoService;
import com.glsc.ngateway.platform.service.costallocation.IpInfoService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

@Service
public class CloudService {

    Logger logger = LoggerFactory.getLogger(CloudService.class);

    @Autowired
    private SequenceService sequenceService;
    @Autowired
    private UserService userService;
    @Autowired
    private ItCloudDeviceRepo itCloudDeviceRepo;
    @Autowired
    private ItCloudListRepo itCloudListRepo;

    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private MailService mailService;
    @Resource
    private IpInfoService ipInfoService;
    @Autowired
    private BusiSystemInfoService busiSystemInfoService;


    public ItCloudDevice findByDevId(String devId) {
        return itCloudDeviceRepo.findByDevId(devId);
    }


    public Page<ItCloudDevice> queryCloudList(Integer page, Integer size, String userId) {
        Pageable pageable = PageRequest.of(page - 1, size);
        Page<ItCloudDevice> list = itCloudDeviceRepo.getCloudDeviceByUser(pageable, userId);
        List<ItCloudDevice> flist = list.getContent();
        try {
            for (ItCloudDevice s : flist) {
                User user = userService.findByUserId(s.getUserId());
                if (user != null) {
                    s.setDepartment(user.getUserDepartment());
                }
            }
        } catch (Exception e) {
            logger.error("queryCloudList异常", e);
        }
        return list;
    }

    public void deleteCloud(String devId) {
        Optional<ItCloudDevice> dev = itCloudDeviceRepo.findById(devId);
        if (dev.isPresent()) {
            dev.get().setMark("2");
            itCloudDeviceRepo.save(dev.get());
        }
    }

    //    public String addCloudServer(Map<String, Object> cloudServerInfo) {
//        String devId = "CS-" + sequenceService.getNextValue("cloud_dev");
//        cloudServerInfo.put("devId", devId);
//        cloudServerInfo.put("mark", "1");
//        Date currentTime = new Date();
//        cloudServerInfo.put("insertTime", currentTime);
////		cloudServerInfo.put("updateTime", currentTime);
//        // change the camel-naming to underline-naming
//        cloudServerInfo = BeanUtil.camel2Underline(cloudServerInfo);
//        generalDataManager.insert("t_cloud_device", cloudServerInfo);
//        return devId;
//    }
//
//    public void updateCloudServer(Map<String, Object> cloudServerInfo) {
//        Date currentTime = new Date();
//        cloudServerInfo.put("insertTime", currentTime);
////		cloudServerInfo.put("updateTime", currentTime);
//        // change the camel-naming to underline-naming
//        cloudServerInfo = BeanUtil.camel2Underline(cloudServerInfo);
//        generalDataManager.update("t_cloud_device", cloudServerInfo, "dev_id");
//    }

    /**
     * 回滚备份
     * @param itCloudDevice
     */
    public void addOrUpdateCloud_back(ItCloudDevice itCloudDevice) {
        boolean isAdd = false;
        if (StringUtils.isEmpty(itCloudDevice.getDevId())) {
            isAdd = true;
            boolean con = true;
            String id = null;
            while (con) {
                String tmpid = "CS-" + sequenceService.getNextValue("cloud_dev");
                logger.info("新增云，生成云唯一标识，临时" + tmpid);
                ItCloudDevice i = itCloudDeviceRepo.findByDevId(tmpid);
                if (i == null) {
                    logger.info("新增云，生成云唯一标识，选中" + tmpid);
                    id = tmpid;
                    con = false;
                }
            }
            itCloudDevice.setDevId(id);
            itCloudDevice.setMark("1");
        }
        if (StringUtils.isNotEmpty(itCloudDevice.getUserAccount())) {
            PlatformUserDto u = userService.findByUsername(itCloudDevice.getUserAccount());
            if (u != null) {
                itCloudDevice.setUserId(u.getUserid());
            } else {
                logger.info("未找到云主机责任人");
//                itCloudDevice.setUserId(null);
            }
        } else {
            User u = userService.findByUserId(itCloudDevice.getUserId());
            if (u == null){
                //增加新用户
                try{
                    userService.addUser(itCloudDevice.getUserId());
                }catch (Exception e){
                    e.printStackTrace();
                    mailService.sendMailToAdmin("IT资产OA回调新增用户失败"+itCloudDevice.getUserId(),e.getMessage());
                }
            }
//            itCloudDevice.setUserId(null);
        }
        try{
            busiSystemInfoService.synchronizeBusiInfoAddOrUpdate(itCloudDevice,isAdd);
        }catch(Exception e){
            logger.info("云平台同步异常-新增或编辑", e);
            String message = e.getMessage();
            if(StringUtils.isBlank(message)){
                message =  Arrays.toString(e.getStackTrace());
            }
            mailService.sendMailToAdmin("云平台同步异常-新增或编辑",message);
        }

        String addORupdate = "add";
        ItCloudDevice oldITserver = new ItCloudDevice();
        if(!isAdd){
            String devId = itCloudDevice.getDevId();
            addORupdate = "update";
            ItCloudDevice temp = findByDevId(devId);
            BeanUtils.copyProperties(temp,oldITserver);
        }
        ItCloudDevice saved = itCloudDeviceRepo.save(itCloudDevice);
        try{
            ipInfoService.synchronizeBaseIpInfoAddOrUpdate(saved,oldITserver,addORupdate);
        }catch(Exception e){
            logger.info("服务器资产同步异常-新增或编辑", e);
            String message = e.getMessage();
            if(StringUtils.isBlank(message)){
                message =  Arrays.toString(e.getStackTrace());
            }
            mailService.sendMailToAdmin("云平台服务器资产同步IP异常-新增或编辑", message);
        }
    }

    public void addOrUpdateCloud(ItCloudDevice itCloudDevice){
        if (StringUtils.isEmpty(itCloudDevice.getDevId())) {
            boolean con = true;
            String id = null;
            while (con) {
                String tmpid = "CS-" + sequenceService.getNextValue("cloud_dev");
                logger.info("新增云，生成云唯一标识，临时" + tmpid);
                ItCloudDevice i = itCloudDeviceRepo.findByDevId(tmpid);
                if (i == null) {
                    logger.info("新增云，生成云唯一标识，选中" + tmpid);
                    id = tmpid;
                    con = false;
                }
            }
            itCloudDevice.setDevId(id);
            itCloudDevice.setMark("1");
        }
        if (StringUtils.isNotEmpty(itCloudDevice.getUserAccount())) {
            PlatformUserDto u = userService.findByUsername(itCloudDevice.getUserAccount());
            if (u != null) {
                itCloudDevice.setUserId(u.getUserid());
            } else {
                logger.info("未找到云主机责任人");
            }
        } else {
            User u = userService.findByUserId(itCloudDevice.getUserId());
            if (u == null){
                //增加新用户
                try{
                    userService.addUser(itCloudDevice.getUserId());
                }catch (Exception e){
                    e.printStackTrace();
                    mailService.sendMailToAdmin("IT资产OA回调新增用户失败"+itCloudDevice.getUserId(),e.getMessage());
                }
            }
        }
        itCloudDeviceRepo.save(itCloudDevice);
    }


    public List<ItCloudList> queryCloudAreaList() {
        return itCloudListRepo.findAll();
    }


    //云平台数据导出

    public List<CloudManageExport> exportCloudOutPut() {
        String sql = "select case when a.cloud_id=0 then '阿里公有云'  " +
                "when a.cloud_id=1 then '阿里金融云' end cloud_id, " +
                "(select dict_value from t_it_dict c where c.zd_id = a.cloud_style) cloud_style, " +
                "list_name cloud_area,inside_ip,eip,slb, " +
                "(select dict_value from t_it_dict d where d.zd_id = a.operation_sys) operation_sys, " +
                "(select dict_value from t_it_dict e where e.zd_id = a.cpu) cpu, " +
                "(select dict_value from t_it_dict f where f.zd_id = a.memory) memory, " +
                "manage_control, master_name, mx_name application, g.name , g.department " +
                "from t_it_cloud_device a " +
                "left join t_it_cloud_list b on a.cloud_area = b.list_id " +
                "left join t_it_application_detail f on a.application = f.mx_id " +
                "left join t_user g on a.user_id = g.userid where mark = '1' ";
        return jdbcTemplate.query(sql, new CloudRowMapper());
    }

    //云平台数据导出
//    public List<CloudDeviceExport> queryCloudOutPut(String scd) {
//        String condition = "";
////		if(scd!=null) {
////			condition+=" and inside_ip=" + scd;
////		}
//        if (scd != null) {
//            condition += " (and inside_ip like '%" + scd + "%' or eip like '%" + scd + "%' or slb like '%" + scd + "%') ";
//        }
//        String sql = "select case when a.cloud_id=0 then '阿里公有云'  " +
//                "when a.cloud_id=1 then '阿里金融云' end cloud_id, " +
//                "(select dict_value from t_dict c where c.zd_id = a.cloud_style) cloud_style, " +
//                "list_name cloud_area,inside_ip,eip,slb, " +
//                "(select dict_value from t_dict d where d.zd_id = a.operation_sys) operation_sys, " +
//                "(select dict_value from t_dict e where e.zd_id = a.cpu) cpu, " +
//                "(select dict_value from t_dict f where f.zd_id = a.memory) memory, " +
//                "manage_control,master_name,mx_name application,user_name user_id,g.department " +
//                "from t_cloud_device a " +
//                "left join t_cloud_list b on a.cloud_area = b.list_id " +
//                "left join t_yinyong_detail f on a.application = f.mx_id " +
//                "left join t_admin_user g on a.user_id = g.user_id where mark = '1' " + condition;
//        return jdbcTemplate.query(sql, new CloudRowMapper());
//    }
//
//    //搜索云平台
//    public List<Map<String, Object>> searchCloud(String scd, String user_id) {
//        //验证user_id的权限是否为admin
//        List<String> userRoles = userService.getUserAllRolesById(user_id);
//        boolean isAuth = false; //是否有权限新增
//        for (String role : userRoles) {
//            if ("admin".equals(role)) {
//                isAuth = true;
//                break;
//            }
//        }
//        String condition = "";
//        String sql = "";
//        if (isAuth) {
//            sql = "select a.*,b.department from t_cloud_device a left join t_admin_user b on a.user_id = b.user_id where a.mark = '1' and (inside_ip like '%" + scd + "%' "
//                    + "or eip like '%" + scd + "%' or slb like '%" + scd + "%') ";
//        } else {
//            condition += " and user_id = '" + user_id + "'";
//            condition += " order by insert_time desc ";
//            sql = "select * from t_cloud_device where mark = '1' and (inside_ip like '%" + scd + "%' "
//                    + "or eip like '%" + scd + "%' or slb like '%" + scd + "%')  " + condition;
//        }
//        return BeanUtil.underline2Camel(jdbcTemplate.queryForList(sql));
//    }
//
//    //搜索云平台名称
//    public List multiSearch(Map<String, Object> cloudServerInfo) {
//        String condition = " where  1=1 ";
//        Integer cloudId = (Integer) cloudServerInfo.get("cloudId");
//        if (cloudId != null) {
//            condition += " and cloud_id = " + cloudId.intValue();
//        }
//        Integer cloudStyle = (Integer) cloudServerInfo.get("cloudStyle");
//        if (cloudStyle != null) {
//            condition += " and cloud_style = " + cloudStyle.intValue();
//        }
//        Integer cloudArea = (Integer) cloudServerInfo.get("cloudArea");
//        if (cloudArea != null) {
//            condition += " and cloud_area = " + cloudArea.intValue();
//        }
//        String application = (String) cloudServerInfo.get("application");
//        if (!"".equals(application) && application != null) {
//            condition += " and application = '" + application + "'";
//        }
//        String userId = (String) cloudServerInfo.get("userId");
//        if (!"".equals(userId) && userId != null) {
//            condition += " and a.user_id = '" + userId + "'";
//        }
//        String sql = "select a.*,b.department from t_cloud_device a left join t_admin_user b on a.user_id = b.user_id " + condition;
//        return BeanUtil.underline2Camel(jdbcTemplate.queryForList(sql));
//    }
//
//
//    public Map<String, Object> getInfo(String devId) {
//        Map<String, Object> conditions = new HashMap<String, Object>();
//        conditions.put("dev_id", devId);
//        return BeanUtil.underline2Camel(generalDataManager.queryForMap("t_cloud_device", conditions));
//    }

    //搜索云平台
    public Page<ItCloudDevice> searchCloud(Integer page, Integer size,
                                           String cloudId, String cloudStyle, Integer cloudArea, String userId, String application) {
        Pageable pageable = PageRequest.of(page - 1, size);
        Page<ItCloudDevice> list = itCloudDeviceRepo.searchCloudDevice(pageable, cloudId, cloudStyle, cloudArea, userId, application);
        List<ItCloudDevice> flist = list.getContent();
        try {
            for (ItCloudDevice s : flist) {
                if (StringUtils.isNotEmpty(s.getUserId())) {
                    User user = userService.findByUserId(s.getUserId());
                    if (user != null) {
                        s.setDepartment(user.getUserDepartment());
                        s.setUserName(user.getName());
                        s.setUserAccount(user.getUsername());
                    }
                }
            }
        } catch (Exception e) {
            logger.error("searchCloud搜索异常", e);
        }
        return list;
    }

}
